package de.haw.HES.base;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import de.haw.HES.Switch.pub.Monitor;

public class DefaultAvailableServer extends Thread implements AvailableServer {

	private Registry registry;
	private Monitor entity;
	private String identifierOfServer;

	public DefaultAvailableServer() {

	}

	public DefaultAvailableServer(String registry, String monitorName,
			String identifierOfServer) {
		setMonitoringInstance(registry, monitorName, identifierOfServer);
	}

	private void setMonitoringInstance(String registry, String monitorName,
			String identifierOfServer) {
		try {
			if (registry == null) {
				this.registry = LocateRegistry.getRegistry();
			} else
				this.registry = LocateRegistry.getRegistry(registry);
		} catch (Exception e) {
			entity = null;
			return;
		}
		try {
			if (monitorName == null) {
				entity = (Monitor) Naming.lookup("Monitor");
			} else {
				entity = (Monitor) Naming.lookup(monitorName);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			entity = null;
			return;
		}
		this.identifierOfServer = identifierOfServer;
	}

	@Override
	public void sendAliveMessage(String identifier) throws RemoteException {
		try {
			if (entity != null) {
				entity.receiveAliveMessage(identifier);
			}
		} catch (Exception e) {
			entity = null;
		}
	}

	@Override
	public void run() {
		while (true) {
			try {
				if(entity==null) {
					setMonitoringInstance(null, null, "Monitor");
				}
				sendAliveMessage(identifierOfServer);
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				Thread.sleep(2000l);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
